import api from './auth'

/**
 * 获取用户所有数据库连接
 */
export const getUserConnections = async () => {
  try {
    const response = await api.get('/api/db-connections')
    return response.data
  } catch (error) {
    throw new Error(error.response?.data?.message || '获取数据库连接失败')
  }
}

/**
 * 获取默认数据库连接
 */
export const getDefaultConnection = async () => {
  try {
    const response = await api.get('/api/db-connections/default')
    return response.data
  } catch (error) {
    throw new Error(error.response?.data?.message || '获取默认数据库连接失败')
  }
}

/**
 * 获取指定ID的数据库连接
 */
export const getConnection = async (id) => {
  try {
    const response = await api.get(`/api/db-connections/${id}`)
    return response.data
  } catch (error) {
    throw new Error(error.response?.data?.message || '获取数据库连接失败')
  }
}

/**
 * 创建数据库连接
 */
export const createConnection = async (connectionData) => {
  try {
    const response = await api.post('/api/db-connections', connectionData)
    return response.data
  } catch (error) {
    throw new Error(error.response?.data?.message || '创建数据库连接失败')
  }
}

/**
 * 更新数据库连接
 */
export const updateConnection = async (id, connectionData) => {
  try {
    const response = await api.put(`/api/db-connections/${id}`, connectionData)
    return response.data
  } catch (error) {
    throw new Error(error.response?.data?.message || '更新数据库连接失败')
  }
}

/**
 * 删除数据库连接
 */
export const deleteConnection = async (id) => {
  try {
    const response = await api.delete(`/api/db-connections/${id}`)
    return response.data
  } catch (error) {
    throw new Error(error.response?.data?.message || '删除数据库连接失败')
  }
}

/**
 * 设置默认连接
 */
export const setDefaultConnection = async (id) => {
  try {
    const response = await api.put(`/api/db-connections/${id}/default`)
    return response.data
  } catch (error) {
    throw new Error(error.response?.data?.message || '设置默认连接失败')
  }
}

/**
 * 测试数据库连接
 */
export const testConnection = async (connectionData) => {
  try {
    const response = await api.post('/api/db-connections/test', connectionData)
    return response.data
  } catch (error) {
    throw new Error(error.response?.data?.message || '测试连接失败')
  }
}

/**
 * 清除连接的元数据缓存
 * @param {Number} connectionId - 数据库连接ID 
 */
export const clearConnectionMetadata = async (connectionId) => {
  try {
    const response = await api.post(`/api/metadata/clear/${connectionId}`)
    return response.data
  } catch (error) {
    throw new Error(error.response?.data?.message || '清除元数据缓存失败')
  }
} 